#!/bin/bash

set -o errexit

test_dir="$(dirname $0)"
. $(dirname $0)/functions
src_dir="$(realpath ${test_dir}/..)"

set_debug

IMAGE=$(echo "$IMAGE" | sed -e 's#percona/#perconalab/#')

if [[ ${DOCKER_NOCACHE:-0} == 1 ]]; then
	no_cache="--no-cache"
fi
if [[ ${DOCKER_SQUASH:-1} == 1 ]]; then
	squash="--squash"
fi

build_operator() {
	if [ "${RELEASE:-1}" = 0 ]; then
		GO_LDFLAGS="-race"
	fi

	export IMAGE
	export DOCKER_DEFAULT_PLATFORM=${DOCKER_DEFAULT_PLATFORM:-linux/amd64}
	export GO_LDFLAGS="-w -s -trimpath $GO_LDFLAGS"
	pushd ${src_dir}
	docker build \
		--build-arg GIT_COMMIT=$GIT_COMMIT \
		--build-arg GIT_BRANCH=$GIT_BRANCH \
		--build-arg BUILD_TIME=$BUILD_TIME \
		--build-arg GO_LDFLAGS="$GO_LDFLAGS" \
		$squash \
		$no_cache \
		--progress plain \
		-t "${IMAGE}" -f build/Dockerfile .
	popd

	if [ "${DOCKER_PUSH:-1}" = 1 ]; then
		docker push ${IMAGE}
	fi
}

if [[ $BUILD == "0" ]]; then
	exit 0
fi

until docker ps; do sleep 1; done
build_operator
